package com.yykt.weshare.util;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池公共基础类
 */
public class ExecutorUtils {

    private static final int EXTRA_THREAD = 3;

    public static Executor getExecutor(String threadNamePrefix, int poolSize) {
        return getExecutor(threadNamePrefix, poolSize + EXTRA_THREAD, new ThreadPoolExecutor.AbortPolicy());
    }

    public static ThreadPoolTaskExecutor getExecutor(String threadNamePrefix, int poolSize
            , RejectedExecutionHandler rejectedExecutionHandler) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(poolSize);
        executor.setMaxPoolSize(poolSize);
        executor.setQueueCapacity(25); // 队列中堆积的任务数量，超过这个数量，就会抛出异常！！！
        executor.setRejectedExecutionHandler(rejectedExecutionHandler);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.initialize();
        return executor;
    }
}
